<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品图片" prop="goodsPicture">
        <el-input
          v-model="queryParams.goodsPicture"
          placeholder="请输入商品图片"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品数量" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入商品数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入商品价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="售卖价格" prop="sellPrice">
        <el-input
          v-model="queryParams.sellPrice"
          placeholder="请输入售卖价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架时间" prop="date">
        <el-date-picker clearable
                        v-model="queryParams.date"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择上架时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="商品种类" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:goods:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goods:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:goods:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品id" align="center" prop="goodsId"/>
      <el-table-column label="商品图片" align="center" prop="goodsPicture">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.goodsPicture"
            :preview-src-list="[scope.row.goodsPicture]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="商品数量" align="center" prop="num" :width="240">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.num" controls-position="left" :min="0" :max="10"/>
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="price"/>
      <el-table-column label="售卖价格" align="center" prop="sellPrice"/>
      <el-table-column label="上架时间" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品种类" align="center" prop="type"/>
      <el-table-column label="库存状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品图片" prop="goodsPicture">
          <el-upload
            class="upload-demo"
            :action="imageUrl"
            :limit='1'
            :on-success="handleSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="商品数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入商品数量"/>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品价格"/>
        </el-form-item>
        <el-form-item label="售卖价格" prop="sellPrice">
          <el-input v-model="form.sellPrice" placeholder="请输入售卖价格"/>
        </el-form-item>
        <el-form-item label="上架时间" prop="date">
          <el-date-picker clearable
                          v-model="form.date"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择上架时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="商品种类" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listGoods, getGoods, delGoods, addGoods, updateGoods} from "@/api/system/goods";
import {changeUserStatus} from "@/api/system/goods";

export default {
  name: "Goods",
  data() {
    return {
      //仓库选项
      options: [{
        value: '选项1',
        label: '闪电仓'
      }, {
        value: '选项2',
        label: '现货仓'
      }, {
        value: '选项3',
        label: '其他'
      }],
      value: 'true',
      //上传链接
      imageUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      //文件
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品库存表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsPicture: null,
        name: null,
        num: null,
        price: null,
        sellPrice: null,
        date: null,
        type: null,
        status: null,
        user: null
      },
      // 表单参数
      form: {
        goodsId: '',
        goodsPicture: '',
        name: '',
        num: '',
        price: '',
        sellPrice: '',
        date: '',
        type: '',
        status: ''
      },
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 移除图片 */
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    /** 点击图片 */
    handlePreview(file) {
      console.log(file);
      this.form.goodsPicture = file.url;
    },
    handleSuccess(response, file, fileList) {
      console.log(file);
      this.form.goodsPicture = file.url;
      file.name = this.form.name;
    },
    /** 查询商品库存列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        goodsPicture: null,
        name: null,
        num: null,
        price: null,
        sellPrice: null,
        date: null,
        type: null,
        status: null,
        user: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品库存";
      this.fileList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsId = row.goodsId || this.ids
      getGoods(goodsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品库存";
        this.fileList = [{name: this.form.name, url: this.form.goodsPicture}];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.goodsId != null) {
            console.log(this.form);
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.status='0';
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$modal.confirm('是否确认删除商品库存编号为"' + goodsIds + '"的数据项？').then(function () {
        return delGoods(goodsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "入库" : "出库";
      this.$modal.confirm('确认要' + text + row.num + '双' + row.name + '吗？').then(function () {
        return changeUserStatus(row.goodsId, row.status, row.num,row.goodsPicture,row.name,row.price,row.sellPrice,row.date,row.type,row.user);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        const obj = { path: "/system/goods", name: "Goods" };
        this.$tab.refreshPage(obj);
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
